package com.heima.wemedia.service.impl;

import com.heima.apis.article.IArticleClient;
import com.heima.model.comment.dtos.CommentManageDto;
import com.heima.model.comment.dtos.CommentPageDto;
import com.heima.model.comment.dtos.StatusCommentDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.thread.WmThreadLocalUtil;

import com.heima.wemedia.pojos.ApComment;
import com.heima.wemedia.pojos.ApCommentLike;
import com.heima.wemedia.pojos.ApCommentRepay;
import com.heima.wemedia.pojos.CommentRepayListVo;
import com.heima.wemedia.service.WmCommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WmCommentServiceImpl implements WmCommentService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IArticleClient iArticleClient;

    /**
     * 展示评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult showListComment(CommentPageDto dto) {

        Integer userID = WmThreadLocalUtil.getUserID();
        dto.setWmUserId(userID);

        //2.远程调用app端文章微服务
        ResponseResult result = iArticleClient.showListComment(dto);

        return result;
    }

    /**
     * 打开或关闭评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatusComment(StatusCommentDto dto) {
        //1.参数检查
        if (dto.getArticleId() == null || dto.getOperation() < 0 || dto.getOperation() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        Integer apUserId = WmThreadLocalUtil.getUserID();
        if (apUserId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.修改文章微服务的评论状态
        iArticleClient.updateStatusComment(dto);

        //3.删除mongodb中相关信息

//        Query entryId = Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("authorId").is(apUserId));

        //获取所有一级评论信息
        List<ApComment> apCommentList = mongoTemplate.find(Query
                .query(Criteria.where("entryId")
                        .is(dto.getArticleId())), ApComment.class);

        for (ApComment apComment : apCommentList) {
            //查询一级评论下关联的二级评论
            List<ApCommentRepay> apCommentRepayList = mongoTemplate.find(Query.query(Criteria
                    .where("commentId")
                    .is(apComment.getId())), ApCommentRepay.class);
            //将二级评论对象集合转为id集合
            List<String> apCommentRepayIds = apCommentRepayList.stream().map(ApCommentRepay::getId).distinct().collect(Collectors.toList());

            //根据一级评论id删除二级评论和点赞信息
            mongoTemplate.remove(Query.query(Criteria.where("commentId").in(apCommentRepayIds)), ApCommentLike.class);
            mongoTemplate.remove(Query.query(Criteria.where("commentId").is(apComment.getId())), ApCommentRepay.class);

            //删除当前一级评论的点赞信息
            mongoTemplate.remove(Query.query(Criteria.where("commentId").is(apComment.getId())), ApCommentLike.class);
        }
        //删除所有的一级评论
        mongoTemplate.remove(Query.query(Criteria.where("entryId")
                .is(dto.getArticleId())), ApComment.class);

//        //删除一级评论和点赞信息
//        mongoTemplate.remove(Query.query(Criteria.where("entryId").is(dto.getArticleId())), ApComment.class);
//        mongoTemplate.remove(Query.query(Criteria.where("commentId").in(apCommentRepayIds)), ApCommentLike.class);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);


    }

    /**
     * 展示文章每条评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listComment(CommentManageDto dto) {

        //1.参数检验
        dto.checkParam();
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        //2.条件参数
//        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()));
//        query.with(PageRequest.of(dto.getPage(),dto.getSize()));
//        query.with(Sort.by(Sort.Direction.DESC,"createdTme"));
//        //3.查询评论数据
//        List<ApComment> apCommentList = mongoTemplate.find(query, ApComment.class);

        List<ApComment> apCommentList = mongoTemplate.find(Query
                .query(Criteria.where("entryId")
                        .is(dto.getArticleId()))
                .skip((dto.getPage() - 1) * dto.getSize())
                .limit(dto.getSize())
                .with(Sort.by(Sort.Direction.DESC, "likes")), ApComment.class);
        List<CommentRepayListVo> list = new ArrayList<>();

        for (ApComment apComment : apCommentList) {

            CommentRepayListVo commentRepayListVo = new CommentRepayListVo();

            commentRepayListVo.setApComments(apComment);
            //4.回复数查找
//            Query query1 = Query.query(Criteria.where("commentId").is(apComment.getId()));
//            query1.with(Sort.by(Sort.Direction.DESC));

            List<ApCommentRepay> apCommentRepayList = mongoTemplate.find(Query
                    .query(Criteria
                            .where("commentId")
                            .is(apComment.getId())
                    ).with(Sort.by(Sort.Direction.DESC, "createdTime")), ApCommentRepay.class);
            commentRepayListVo.setApCommentRepays(apCommentRepayList);
            //5.封装返回
            list.add(commentRepayListVo);
        }

        return ResponseResult.okResult(list);


    }
}
